var gulp = require('gulp'),
  path = require('path'),
  glob = require("glob"),
  clean = require('gulp-clean'),
  rename = require('gulp-rename'),
  rev = require('gulp-rev'), // 加版本号
  revCollector = require('gulp-rev-collector'), // 替换路径
  minimist = require('minimist'),
  gulpIf = require('gulp-if'),
  sourcemaps = require('gulp-sourcemaps'),
  plumber = require('gulp-plumber');

// html
var ejs = require('gulp-ejs'),
  htmlmin = require('gulp-htmlmin');

// css
var sass = require('gulp-sass'),
  cleanCSS = require('gulp-clean-css'),
  autoprefixer = require('gulp-autoprefixer');

// js
var uglify = require('gulp-uglify');

//image
var image = require('gulp-image');

var BUILD_DIR = {
  src: 'src/',
  temp: 'src/temp',
  rev: 'src/rev/',
  debug: 'debug/',
  release: 'dist/'
}, BUILD_DIST = BUILD_DIR.debug;

// 生产环境为true，开发环境为false，默认为false
var env = false;

// 定制参数
var custom = 'standard';
var options = minimist(process.argv.slice(2));
var optM = options['m'], optR = options['r'];
if (typeof optM === 'string') custom = optM;
if (optR) {
  env = true;
  BUILD_DIST = BUILD_DIR.release;
}

gulp.task('help', function () {
  console.log('    help                gulp参数说明');

  console.log('    build               文件打包，默认打包到开发目录');

  console.log('    -r                  打包到生产目录');

  console.log('    watch               监控文件，自动打包');

  console.log('    clean               清空打包目录');

  console.log('    compileEjs          编译EJS模板');

  console.log('    sass                编译SASS文件');

  console.log('    -m                  定制版');
});
gulp.task('default', function () {
  gulp.start('help');
});

gulp.task('clean', function () {
  gulp.src([
    BUILD_DIST,
    BUILD_DIR.rev
  ])
    .pipe(clean({force: true}))
});


gulp.task('compileEjs', options['_'][0] === 'build' ? ['revCollectorCss', 'revCollectorJs'] : [], function () {
  gulp.src([
    'src/rev/**/*.json',
    'src/module/**/*.ejs',
    path.join('src', (custom === 'standard' ? 'standard' : 'template/' + custom), '**/*.ejs'), // 保证定制版覆盖标准版
    '!src/**/_*.ejs'])
    .pipe(plumber())
    .pipe(revCollector())
    .pipe(ejs())
    .pipe(rename(function (path) {
      path.extname = ".html"
    }))
    .pipe(gulpIf(env, htmlmin({collapseWhitespace: true})))
    .pipe(gulp.dest(path.join(BUILD_DIST, custom)));
});

gulp.task('sass', function () {
  return gulp.src(path.join('src/module', '**/*.scss'))
    .pipe(plumber())
    .pipe(sass({outputStyle: env ? 'compressed' : 'expanded'}).on('error', sass.logError))
    .pipe(autoprefixer('last 2 version', 'safari 5', 'ie 8', 'ie 9', 'opera 12.1'))
    .pipe(rename(function (path) {
      path.dirname = path.dirname.replace('sass', 'css');
    }))
    .pipe(rev())
    .pipe(gulp.dest(path.join(BUILD_DIST, custom)))
    .pipe(rev.manifest())
    .pipe(gulp.dest(path.join(BUILD_DIR.rev, 'css')));
});

gulp.task('revCollectorCss', ['sass'], function () {
  return gulp.src([
    path.join(BUILD_DIR.rev, 'image/rev-manifest.json'),
    path.join(BUILD_DIST, custom, '/**/*.css'),
    path.join('!' + BUILD_DIST, custom, '/**/lib/**/*.css')
  ])
    .pipe(revCollector())
    .pipe(gulp.dest(path.join(BUILD_DIST, custom)));
});

gulp.task('copyJs', function () {
  return gulp.src(['src/module/**/*.js', '!src/module/**/lib/**/*'])
    .pipe(plumber())
    .pipe(sourcemaps.init())
    .pipe(gulpIf(env, uglify()))
    .pipe(rev())
    .pipe(sourcemaps.write())
    .pipe(gulp.dest(path.join(BUILD_DIST, custom)))
    .pipe(rev.manifest())
    .pipe(gulp.dest(path.join(BUILD_DIR.rev, 'js')));
});

gulp.task('revCollectorJs', ['copyJs'], function () {
  return gulp.src([
    path.join(BUILD_DIR.rev, 'js/rev-manifest.json'),
    path.join(BUILD_DIST, custom, '**/*.js'),
    path.join('!' + BUILD_DIST, custom, '**/lib/**/*')])
    .pipe(plumber())
    .pipe(revCollector())
    .pipe(gulp.dest(BUILD_DIST + custom));
});

gulp.task('copyLib', function () {
  gulp.src('src/module/public/js/lib/**/*', {base: 'src/module'})
    .pipe(gulp.dest(BUILD_DIST + custom));
});

gulp.task('imageMin', function () {
  gulp.src([
    'src/module/**/*.+(png|jpg|jpeg|gif)',
    '!src/module/**/lib/**/*'
  ])
    .pipe(gulpIf(env, image()))
    .pipe(rev())
    .pipe(gulp.dest(path.join(BUILD_DIST, custom)))
    .pipe(rev.manifest())
    .pipe(gulp.dest(path.join(BUILD_DIR.rev, 'image')));
});

gulp.task('build', function () {
  gulp.start('copyLib', 'imageMin', 'compileEjs');
});

gulp.task('watch', ['copyLib', 'imageMin', 'revCollectorCss', 'revCollectorJs', 'compileEjs'], function () {
    gulp.watch('src/**/*.ejs', ['compileEjs']);
    gulp.watch('src/module/**/*.scss', ['revCollectorCss']);
    gulp.watch(['src/module/**/*.js', '!src/module/public/js/lib/**/*'], ['revCollectorJs']);
    gulp.watch('src/module/public/js/lib/**/*', ['copyLib']);
    gulp.watch(['src/module/**/*.+(png|jpg|jpeg|gif)', '!src/module/**/lib/**/*'], ['imageMin'])
  }
);